package list;

/**题目：删除链表倒数第k个元素
 * @Author Gavin
 * @date 2022.01.03 09:52
 */
public class list_8 {
    //Time:O(n) Space:O(1)
    public ListNode solution(ListNode head,int k){
        ListNode dummy=new ListNode(-1);
        dummy.next=head;
        ListNode p=dummy,q=dummy;
        while (k>0&&p.next!=null)p=p.next;k--;
        if(k>0)return null;//说明k大于链表的长度

        while (p.next!=null){
            q=q.next;
            p=p.next;
        }
        q.next=q.next.next;//q.next就是倒数第k个元素
        return dummy.next;
    }
}
